package com.hui.tset01.service.impl;

import com.hui.tset01.domain.dto.UserDto;
import com.hui.tset01.domain.po.User;
import com.hui.tset01.domain.vo.UserVo;
import com.hui.tset01.mapper.UserMapper;
import com.hui.tset01.service.UserService;
import com.hui.tset01.util.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;

    /**
     * 登录
     */
    @Override
    public UserVo login(UserDto userDto) {
        //判断是否有该用户
        User user = userMapper.selectUserByUserName(userDto.getUserName());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        //判断密码是否正确
        if (!user.getPassword().equals(userDto.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        //返回用户信息
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        String token = JwtUtil.creatJwt(claims);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        userVo.setToken(token);
        return userVo;
    }
}
